<?php

namespace App\Jobs;
// 加载采集环境

use App\Models\Posts\WxTag;
use App\Wen\Utils\ImageUtils;
use App\Wen\Utils\Settings;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use QL\QueryList;

class TopicImgJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $topic_id = 0;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($topic_id)
    {
        //
        $this->topic_id = $topic_id;
    }

    /**
     * @param $keyword
     * @param int[] $rates 高宽比
     * @return array|null
     */
    public function get_bing_some_rate_imgs($keyword, $rates = [1]){

        if(_empty_($keyword)){
            return null;
        }

        if(Settings::get('is_tag_match_img', 0) != 1){
            return null;
        }

        $img_data = $this->get_bing_search_imgs($keyword);

        if($img_data){
            $ims_result = [];
            foreach ($rates as $key => $need_rate){
                $min_index = 0;
                $min_ration = 100;
                $i = 0;
                foreach ($img_data['hwr'] as $hwr){
                    if(_abs($need_rate - $hwr) < $min_ration){
                        $min_ration = $hwr;
                        $min_index = $i;
                    }
                    $i ++;
                }
                try{
                    $ims_result[$key] = $img_data['imgs'][$min_index];
                }catch (\Exception $e){
                    _logger_(__file__, __line__, $img_data);
                    _logger_(__file__, __line__, $e->getMessage());
                    return null;
                }

            }
            return $ims_result;
        }
        return null;
    }

    /** bing搜索图片，返回图片地址以及高宽比
     * @param $key
     * @return array[]|null
     */
    public function get_bing_search_imgs($key){

        $headers = [
            'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 UBrowser/6.1.2107.204 Safari/537.36',
        ];
        $url =  "https://cn.bing.com/images/async?q=".$key."&first=1&count=35&scenario=ImageBasicHover&datsrc=N_I&mmasync=1&dgState=c*9_y*2226s2180s2072s2043s2292s2295s2079s2203s2094_i*71_w*198&IG=0D6AD6CBAF43430EA716510A4754C951&SFX=1&iid=images.5599";
        $response = Http::withHeaders($headers)->get($url);
        if($response->successful()){
            $content = $response->body();
            $querry_data = QueryList::html($content)->rules([ 'imgurl' => ['a.iusc', 'href'],
                'size'=> ['a.iusc', 'style']
            ])->range('li')->queryData();
            if(empty($querry_data)){
                return null;
            }

            $new_img_urls = [];
            $h_w_rations = [];
            foreach ($querry_data as $data){
                $url = $data['imgurl'];
                $size = $data['size'];
                preg_match('/&mediaurl=([^&]+?)&/', urldecode($url), $matchs);
                if(!empty($matchs[1])){
                    $url = $matchs[1];
                }else{
                    $url = '';
                }

//            height:245px;width:296px
                $size = urldecode($size);
                preg_match('/height:(\d+?)px;\s?width:(\d+?)px/', $size, $matchs_size);
                if(!empty($matchs_size)){
                    $height = $matchs_size[1];
                    $width = $matchs_size[2];
                    $h_w_ration = round($height / $width, 2);
                }else{
                    $h_w_ration = 0;
                }

                if($url){
                    $new_img_urls[] = $url;
                    $h_w_rations[] = $h_w_ration;
                }
            }
            return ['imgs'=> $new_img_urls,'hwr'=> $h_w_rations];
        }
        return null;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        global $__MINI_GLOBAL_PAYCODE_0__;
        if(!$__MINI_GLOBAL_PAYCODE_0__){
            return;
        }

        if(_empty_($this->topic_id)){
            return;
        }
        if(Cache::has('TopicImgJob:id:'.$this->topic_id)){
            return;
        }
        $tag = WxTag::find($this->topic_id);
        if($tag){
            $adjunct_word = Settings::get('about_adjunct_word');
            $key_word = $adjunct_word ? ($tag->tags_name . ' ' . $adjunct_word) : $tag->tags_name;
            $rates = [];
            if(_empty_($tag->head_portrait)){
                $rates['head_portrait'] = 1;
            }
            if(_empty_($tag->background_maps)){
                $rates['background_maps'] = 0.75;
            }
            $imgs = $this->get_bing_some_rate_imgs($key_word, $rates);
            Cache::put('TopicImgJob:id:'.$this->topic_id, 1, 7200);
            if($imgs){
                if( _array_key($imgs, 'head_portrait', '') ){
                    $path = ImageUtils::upload_url_img($imgs['head_portrait'], '', [], [200, 200], true);
                    if($path && $path['url']){
                        $tag->head_portrait = $path['url'];
                    }
                }
                if( _array_key($imgs, 'background_maps', '') ){
                    $path = ImageUtils::upload_url_img($imgs['background_maps'], '', [], [500, 375], true);
                    if($path && $path['url']){
                        $tag->background_maps = $path['url'];
                    }
                }
                $tag->save();
            }
        }
    }
}
